package com.aiguigu.lottery.prize.service.impl;

import com.aiguigu.lottery.common.entity.PrizeEntity;
import com.aiguigu.lottery.common.entity.PrizeRecordEntity;
import com.aiguigu.lottery.common.entity.UserEntity;
import com.aiguigu.lottery.prize.mapper.PrizeMapper;
import com.aiguigu.lottery.prize.mapper.PrizeRecordMapper;
import com.aiguigu.lottery.prize.mapper.UserMapper;
import com.aiguigu.lottery.prize.service.PrizeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class PrizeServiceImpl implements PrizeService {
    
    private static final Logger logger = LoggerFactory.getLogger(PrizeServiceImpl.class);
    
    @Autowired
    private PrizeMapper prizeMapper;
    
    @Autowired
    private PrizeRecordMapper prizeRecordMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public boolean createPrize(PrizeEntity prize, Integer userId) {
        if (!hasManagePermission(userId)) {
            return false;
        }
        
        prize.setCreateTime(new Date());
        prize.setUpdateTime(new Date());
        prize.setCreatedBy(userId);
        
        // 设置默认状态为启用
        if (prize.getStatus() == null) {
            prize.setStatus(1);
        }
        
        return prizeMapper.insert(prize) > 0;
    }
    
    @Override
    public boolean createPrizeByUsername(PrizeEntity prize, String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null || !hasManagePermission(user.getId())) {
            return false;
        }
        
        prize.setCreateTime(new Date());
        prize.setUpdateTime(new Date());
        prize.setCreatedBy(user.getId());
        
        // 设置默认状态为启用
        if (prize.getStatus() == null) {
            prize.setStatus(1);
        }
        
        return prizeMapper.insert(prize) > 0;
    }
    
    @Override
    public boolean updatePrize(PrizeEntity prize, Integer userId) {
        if (!hasManagePermission(userId)) {
            return false;
        }
        
        prize.setUpdateTime(new Date());
        return prizeMapper.updateById(prize) > 0;
    }
    
    @Override
    public boolean updatePrizeByUsername(PrizeEntity prize, String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null || !hasManagePermission(user.getId())) {
            return false;
        }
        
        prize.setUpdateTime(new Date());
        return prizeMapper.updateById(prize) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePrize(Integer prizeId, Integer userId) {
        if (!hasManagePermission(userId)) {
            return false;
        }
        
        // 先删除相关的中奖记录
        prizeRecordMapper.deleteByPrizeId(prizeId);
        
        // 再删除奖品
        return prizeMapper.deleteById(prizeId) > 0;
    }
    
    @Override
    @Transactional
    public boolean deletePrizeByUsername(Integer prizeId, String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null || !hasManagePermission(user.getId())) {
            return false;
        }
        
        // 先删除相关的中奖记录
        prizeRecordMapper.deleteByPrizeId(prizeId);
        
        // 再删除奖品
        return prizeMapper.deleteById(prizeId) > 0;
    }
    
    @Override
    public List<PrizeEntity> getAllEnabledPrizes() {
        return prizeMapper.findAllEnabled();
    }
    
    @Override
    public List<PrizeEntity> getAllPrizes(Integer userId) {
        if (!hasManagePermission(userId)) {
            return null;
        }
        
        return prizeMapper.findAll();
    }
    
    @Override
    public List<PrizeEntity> getAllPrizesByUsername(String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null || !hasManagePermission(user.getId())) {
            return null;
        }
        
        return prizeMapper.findAll();
    }
    
    @Override
    public List<PrizeEntity> getAllPrizes() {
        return prizeMapper.findAll();
    }
    
    @Override
    @Transactional
    public PrizeEntity drawPrize(Integer userId) {
        // 获取有库存的启用奖品
        List<PrizeEntity> enabledPrizes = prizeMapper.findAvailablePrizes();
        if (enabledPrizes.isEmpty()) {
            logger.warn("没有可用的奖品（库存为0或已禁用），用户ID: {}", userId);
            return null;
        }
        
        // 计算总概率
        double totalProbability = enabledPrizes.stream()
                .mapToDouble(prize -> prize.getProbability() != null ? prize.getProbability() : 0.0)
                .sum();
        
        if (totalProbability <= 0) {
            return null; // 没有有效的奖品概率
        }
        
        // 生成随机数
        double randomValue = Math.random() * totalProbability;
        double currentProbability = 0;
        PrizeEntity selectedPrize = null;
        
        for (PrizeEntity prize : enabledPrizes) {
            double prizeProbability = prize.getProbability() != null ? prize.getProbability() : 0.0;
            currentProbability += prizeProbability;
            if (randomValue <= currentProbability) {
                selectedPrize = prize;
                break;
            }
        }
        
        // 如果没有选中任何奖品，选择第一个
        if (selectedPrize == null) {
            selectedPrize = enabledPrizes.get(0);
        }
        
        // 扣减库存（原子操作）
        if (selectedPrize != null) {
            int stockReduced = prizeMapper.decreaseStock(selectedPrize.getId());
            if (stockReduced == 0) {
                logger.warn("奖品库存不足，无法扣减，奖品ID: {}, 用户ID: {}", selectedPrize.getId(), userId);
                return null; // 库存不足，抽奖失败
            }
            
            // 注释掉直接保存记录的代码，改为由消息队列统一处理
            // 这样避免了重复保存记录的问题
            logger.info("抽奖成功，用户ID: {}, 奖品: {}, 剩余库存: {}", 
                       userId, selectedPrize.getName(), 
                       prizeMapper.checkStock(selectedPrize.getId()));
        }
        
        return selectedPrize;
    }
    
    @Override
    @Transactional
    public PrizeEntity drawPrizeByUsername(String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        
        return drawPrize(user.getId());
    }
    
    @Override
    public PrizeEntity drawPrize() {
        List<PrizeEntity> enabledPrizes = prizeMapper.findAllEnabled();
        if (enabledPrizes.isEmpty()) {
            return null;
        }
        
        // 计算总概率
        double totalProbability = enabledPrizes.stream()
                .mapToDouble(prize -> prize.getProbability() != null ? prize.getProbability() : 0.0)
                .sum();
        
        // 生成随机数
        double randomValue = Math.random() * totalProbability;
        
        // 根据概率选择奖品
        double currentProbability = 0;
        PrizeEntity selectedPrize = null;
        
        for (PrizeEntity prize : enabledPrizes) {
            double prizeProbability = prize.getProbability() != null ? prize.getProbability() : 0.0;
            currentProbability += prizeProbability;
            if (randomValue <= currentProbability) {
                selectedPrize = prize;
                break;
            }
        }
        
        // 如果没有选中任何奖品，选择第一个
        if (selectedPrize == null && !enabledPrizes.isEmpty()) {
            selectedPrize = enabledPrizes.get(0);
        }
        
        return selectedPrize;
    }
    
    @Override
    public boolean savePrizeRecord(PrizeRecordEntity record) {
        try {
            return prizeRecordMapper.insert(record) > 0;
        } catch (Exception e) {
            logger.error("保存中奖记录失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean deletePrizeRecordByUsername(Integer recordId, String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null || !hasManagePermission(user.getId())) {
            return false;
        }
        return prizeRecordMapper.deleteById(recordId.longValue()) > 0;
    }
    
    @Override
    public List<PrizeRecordEntity> getPrizeRecordsByUsername(String username) {
        UserEntity user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        return prizeRecordMapper.findByUserId(user.getId());
    }
    
    @Override
    public List<PrizeRecordEntity> getUserPrizeRecords(Integer userId) {
        return prizeRecordMapper.findByUserId(userId);
    }
    
    @Override
    public List<PrizeRecordEntity> getUserPrizeRecords(String username) {
        return getPrizeRecordsByUsername(username);
    }
    
    @Override
    public List<PrizeRecordEntity> getAllPrizeRecords(Integer userId) {
        if (!hasManagePermission(userId)) {
            return null;
        }
        return prizeRecordMapper.findAllWithDetails();
    }
    
    @Override
    public List<PrizeRecordEntity> getAllPrizeRecords() {
        return prizeRecordMapper.findAllWithDetails();
    }
    
    @Override
    public List<PrizeRecordEntity> getPrizeRecordsByUserId(Integer userId) {
        return prizeRecordMapper.findByUserId(userId);
    }
    
    @Override
    @Transactional
    public boolean deletePrizeRecord(Integer recordId, Integer userId) {
        if (!hasManagePermission(userId)) {
            return false;
        }
        return prizeRecordMapper.deleteById(recordId.longValue()) > 0;
    }
    
    @Override
    public boolean hasManagePermission(Integer userId) {
        UserEntity user = userMapper.findById(userId);
        return user != null && user.getJob() == 1;
    }
    
    // 库存管理相关方法实现
    @Override
    public Integer checkPrizeStock(Integer prizeId) {
        return prizeMapper.checkStock(prizeId);
    }
    
    @Override
    @Transactional
    public boolean decreasePrizeStock(Integer prizeId) {
        return prizeMapper.decreaseStock(prizeId) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePrizeStock(Integer prizeId, Integer total, Integer remaining) {
        return prizeMapper.updateStock(prizeId, total, remaining) > 0;
    }
    
    @Override
    public List<PrizeEntity> getAvailablePrizes() {
        return prizeMapper.findAvailablePrizes();
    }
    
    @Override
    @Transactional
    public boolean batchUpdatePrizeStock(List<PrizeEntity> prizes) {
        try {
            for (PrizeEntity prize : prizes) {
                if (prize.getId() != null && prize.getTotal() != null && prize.getRemaining() != null) {
                    prizeMapper.updateStock(prize.getId(), prize.getTotal(), prize.getRemaining());
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("批量更新奖品库存失败: {}", e.getMessage(), e);
            throw new RuntimeException("批量更新奖品库存失败", e);
        }
    }
}